package com.aaa.service.impl;

import com.aaa.entity.Permission;
import com.aaa.entity.User;
import com.aaa.mapper.PermissionMapper;
import com.aaa.service.PermissionService;
import com.aaa.util.WebUtil;
import com.aaa.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: qy158-system
 * @description:
 * @author: 闫克起2
 * @create: 2022-10-10 11:45
 **/
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public Result findByUserId() {
        User user = (User) WebUtil.getSession().getAttribute("user");
        List<Permission> permissions = permissionMapper.selectByUserId(user.getUserId());
        List<Permission> firsts = firsts(permissions);
        return new Result(2000,"查询左侧菜单成功",firsts);
    }

    private List<Permission> firsts(List<Permission> permissions){
        //1.一级菜单
        List<Permission> firsts=new ArrayList<>();
        for (Permission permission:permissions){
            if(permission.getPid()==0){
                firsts.add(permission);
            }
        }

        //2.查询一级菜单下的二级菜单
        for(Permission first:firsts){
            List<Permission> children=new ArrayList<>();
            for(Permission p:permissions){
                if(first.getId().equals(p.getPid())){
                    children.add(p);
                }
            }
            first.setChildren(children);
        }
        return firsts;
    }

    @Override
    public Result findByRoleId(int roleId) {
        //1.查询所有权限----而且必须有层级关系
        List<Permission> permissions = permissionMapper.selectAll();
        List<Permission> firsts = firsts(permissions);
        //2.根据角色id查询该角色具有的权限id
        List<Integer> permissionIds = permissionMapper.selectByRoleId(roleId);

        Map<String,Object> map=new HashMap<>();
        map.put("firsts",firsts);
        map.put("permissionIds",permissionIds);
        return new Result(2000,"查询成功",map);
    }

    @Override
    public Result qr(Integer roleId, Integer[] permissionIds) {
        //1. 删除该角色具有的权限
        permissionMapper.deleteByRoleId(roleId);
        //2. 批量添加权限
        permissionMapper.batchPermission(roleId,permissionIds);
        return new Result(2000,"分配成功");
    }
}
